//
//  RateManager.swift
//  ImGuider X
//
//  Created by 陆涛 on 2018/10/12.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class RateManager: NSObject {
    
    /// 单例对象
    static let share = RateManager()
    var rateList:[Rate]?
    
    var rateDict:[String:[Rate]] = [:]
    var rateFistLetterArray:[String] = []

    var toastText:((String?)-> Void)?
    var loadFinished:(()->Void)?
    
    var dealRateListFinished:(()->Void)?
    
    var reloadStoreFinished:(()->Void)?
    
    /// 基础美元金额
    var basemoney:Float?

}

extension RateManager {
    
    func reloadData() {
        
        if self.rateList?.count ?? 0 > 0 {
            
            self.loadFinished?()
            return
        }
        
        NetAPI.forex.request([Rate].self) {
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            if let response = response as? [Rate] {
                
                self.rateList = response
            } else {
                
                self.toastText?(errmsg)
            }
            
            self.loadFinished?()
        }
    }
    
    
    /// 存储的key
    var storeKeysList:[String] {
        
        set {
            
            UserDefaults.standard.set(newValue, forKey: "storeRateList")
            UserDefaults.standard.synchronize()
        }
        
        get {
            
            if let array = UserDefaults.standard.array(forKey: "storeRateList") as? [String] {
                
                return array
            }
            
            return ["CNY","USD","EUR"]
            
        }
    }
    
    /// 存取Rate
    var storeRateList:[Rate]? {
        
        guard let ratelist = rateList else { return nil }
        
        let storeKeyList = self.storeKeysList
        
        
        var newList:[Rate] = []
        
        for code in storeKeyList {
            
            if let rate = ratelist.filter({$0.code == code }).first {
                
                newList.append(rate)
            }
        }
        
        return newList
    }
    
    func storRate(new:Rate, old: Rate ) {
        
        var newRateKeyList:[String] = []
        
        for rate in storeRateList ?? [] {
            
            if rate.code == old.code {
                
                if let code = new.code {
                    
                    newRateKeyList.append(code)
                }
                
                
            } else {
                
                if let code = rate.code {
                    
                    newRateKeyList.append(code)
                }
            }
        }
        
        self.storeKeysList = newRateKeyList
    }
    
}

extension RateManager {
    
    /// 将rate处理成特定格式
    func dealRateList() {
        
        if self.rateFistLetterArray.count > 0 {
            
            self.dealRateListFinished?()
            return
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            
            [weak self] in
            guard let `self` = self, let ratelist = self.rateList else { return }
            
            for rate in ratelist {
                
                var initial = rate.smartName?.firstLetter ?? "#"
                
                if (rate.frequent ?? 0) == 1{
                    
                    initial = "#"
                }
                
                if var array = self.rateDict[initial] {
                    
                    array.append(rate)
                    self.rateDict[initial] = array
                    continue
                }
                
                var array:[Rate] = []
                array.append(rate)
                self.rateFistLetterArray.append(initial)
                self.rateDict[initial] = array
            }
            
            self.rateFistLetterArray.sort()
            
            DispatchQueue.main.async {
                
                self.dealRateListFinished?()
            }
        }
//        DispatchQueue.global().async {
//
//
//        }
    }
    
    func calcRealMoney(rate:Rate) -> String? {
        
        guard let r = rate.rate else {
         
            return nil
        }
        
        var basemoney:Float = 100
        
        if let money = self.basemoney {
            
            basemoney = money
        }
        
        let realmoney = basemoney * r
        
        return NSNumber(value: realmoney).stringValue
    }
    
    
    /// 计算输入的s钱对应的美元价值
    ///
    /// - Parameters:
    ///   - rate: 汇率对象
    ///   - money: 输入的钱
    func calcBaseMoney(rate:Rate,money:String?) {
        
        guard let money = money, money.count > 0,
            let realmoney = Float(money),
        let r = rate.rate else {
            
            self.basemoney = nil
            return
        }
        
        self.basemoney = realmoney / r
    }
}

